<?php

namespace HelloWeb\UserBundle\Controller;

use Library\BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use HelloWeb\UserBundle\Entity\User;
use HelloWeb\UserBundle\Form\UserForm;

class UserController extends BaseController
{
    /**
     * list all available users
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @return type
     */
    public function indexAction(Request $request)
    {
        $searchArray = array();
//         $searchArray = $request->request->get('search');
//         if ($searchArray && array_key_exists('cancel', $searchArray)) {
//             $searchArray = null;
//         }
        
        // Fetch results
        /** @var EmailTemplateService $emailTemplateService */
        $userService = $this->get('hello_web.user');
        $users = $userService->getAllUsers(
            $searchArray,
            false,
            false);
        
        // Paginate results
        $paginator = $this->get('knp_paginator');
        $usersPagination = $paginator->paginate(
            $users,
            $request->query->get('page', 1)
        );
        
        // Render
        return $this->render('HelloWebUserBundle:User:index.html.twig', array(
            'usersPagination' => $usersPagination,
            'searchArray' => $searchArray
        ));
    }
    
    /**
     * Add new user
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @return type
     */
    public function addAction(Request $request){
        return $this->editAction($request);
    }
    
    /**
     * edit a exist user
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param int $id
     * @return type
     */
    public function editAction(Request $request, $id=0){
        $userService = $this->get('hello_web.user');
        if($id > 0){
            $user = $userService->getUser(array('id'=>$id));
        }else{
            $user = new User();
        }
        
        //create Form
        $form = $this->createForm(new UserForm(),$user);
        
        if($request->isMethod("POST")){
            $form->handleRequest($request);
            if($form->isValid()){
                $userService->saveUser($user);
                
                if($id > 0){
                    $this->setFlashBag('success',"Successfuly update user.");
                }else{
                    $this->setFlashBag('success',"Successfuly create user.");
                }
                
                return new RedirectResponse($this->generateUrl('admin_user_index'),302);
            }
            
        }
        
        return $this->render('HelloWebUserBundle:User:edit.html.twig',array(
            'form'=>$form->createView(),
            'id'=>$id
        ));
    }
}
